package com.graduationdesign.zengyan.graduationdesignapp.ui.base;


import android.support.annotation.NonNull;

import com.graduationdesign.zengyan.graduationdesignapp.dataLayer.base.Result;
import com.graduationdesign.zengyan.graduationdesignapp.ui.base.errorhandle.ServerException;

import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by ZengYan on 2018/3/20.
 *
 * @desc :
 */

public class Transforms {

    public static <T> ObservableTransformer<Result<T>, Result<T>> applyLoading(BaseLoadingView mLoading) {
        if (mLoading == null) {
            return upstream -> upstream;
        }

        return upstream -> upstream
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    if (mLoading != null) {
                        mLoading.startLoading();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnTerminate((Action) () -> {

                    if (mLoading != null) {
                        mLoading.stopLoading();
                    }
                });
    }


    public static <T> ObservableTransformer<Result<T>, Result<T>> applyAll(BaseLoadingView mLoading,@NonNull CompositeDisposable disposable) {
        return upstream -> upstream
                .compose(applySchedulers())
                .compose(Transforms.applyLoading(mLoading))
                .compose(catchError())
                .compose(addToCompositeDisposable(disposable));
    }

    public static <T> ObservableTransformer<Result<T>, Result<T>> catchError() {
        return upstream -> upstream
                .doOnNext(result -> {
                    if (!result.isSuccessful())  throw new ServerException(result.getCode(), result.getMessage());
                });
    }

    public static <T> ObservableTransformer<Result<T>,Result<T>> applySchedulers() {
        return upstream -> upstream
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public static <T> ObservableTransformer<Result<T>, Result<T>> addToCompositeDisposable(@NonNull  CompositeDisposable compositeDisposable) {
        if (compositeDisposable == null) return upstream -> upstream;

        return upstream -> upstream
                .doOnSubscribe(disposable -> {
                    compositeDisposable.add(disposable);
                });
    }


}
